# 邮箱验证功能
import datetime
import random
from smtplib import SMTP_SSL
from email.mime.text import MIMEText
from django.utils import timezone
from Login import models
from email.utils import formataddr


def createCode():
    str1 = '0123456789'
    str2 = '0123456789'
    str3 = str1 + str2
    codeList = random.sample(str3, 6)
    code = "".join(codeList)
    return code


# 向邮箱发送验证码
def sendMessageByEmail(email):
    try:
        latestCode = models.Code.objects.filter(email=email).order_by('-create_time').first()
        if latestCode:
            latestCodeCreateTime = latestCode.create_time
            latestCodeStatus = latestCode.status
            nowTime = timezone.now()
            if (nowTime < latestCodeCreateTime + datetime.timedelta(minutes=1)) and latestCodeStatus == 1:
                return "请不要一分钟之内连续获取两次验证码"

        code = createCode()  # 生成验证码
        createTime = timezone.now()

        db_code = models.Code(email=email, create_time=createTime, code=code)  # 将验证码保存到数据表中
        db_code.save()

        myEmail = '1547583188@qq.com'  # 发件人邮箱
        myPassword = 'pqaduvnsjnnsjefh'  # 发件人邮箱授权码
        subject = "QueryMatrix AI:洞察问道验证码"  # 邮箱主题名
        text = f"你的验证码为：{code}，5分钟之内有效，为了安全，请不要轻易将验证码告诉他人！"  # 邮箱内容

        message = MIMEText(text, "plain", "utf-8")  # 文本内容，文本格式，编码
        message["Subject"] = subject  # 邮箱主题
        message["From"] = formataddr(["QueryMatrix AI:洞察问道", myEmail])  # 发送者
        message["To"] = formataddr(["XXX", email])  # 接收者

        smtp = SMTP_SSL("smtp.qq.com")  # 需要发送者QQ邮箱开启SMTP服务
        smtp.login(myEmail, myPassword)
        smtp.sendmail(myEmail, email, message.as_string())  # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
        smtp.quit()
        return "验证码发送成功"
    except Exception as e:
        print(e)
        return "验证码发送失败"
